package com.ceair.mub2c.payment.payments.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.ceair.flight.booking.rq.PurchasePointsReq;
import com.ceair.flight.booking.rs.PurchasePointsRes;
import com.ceair.flight.booking.rs.PurchasePointsVO;
import com.ceair.flight.booking.service.IPurchasePointsService;
import com.ceair.flight.query.newOrder.dto.BookingOrderDto;
import com.ceair.flight.query.newOrder.param.BookingOrderMoreParam;
import com.ceair.flight.query.service.IFlightOrderService;
import com.ceair.mub2c.common.user.UserContext;
import com.ceair.mub2c.common.user.UserInfoBean;
import com.ceair.mub2c.common.utils.GlobalExceptionConstants;
import com.ceair.mub2c.common.utils.HttpUtils;
import com.ceair.mub2c.exceptionhandler.ActionException;
import com.ceair.mub2c.exceptionhandler.BaseExceptionController;
import com.ceair.mub2c.payment.payments.service.PurchasePointsDubboService;
import com.ceair.mub2c.payment.payments.vo.PurchasePointsDetailsResultVO;
import com.ceair.unified.businessobject.rqrs.unicfg.UniConfigRS;
import com.ceair.unified.businessobject.rqrs.unicfg.UniRateRQ;
import com.ceair.unified.ws.unicfgmanager.IUniConfigManagerWS;

@Controller
@RequestMapping(value = "/payment")
public class PurchasePointsController extends BaseExceptionController {
	private static final Log log = LogFactory.getLog(PurchasePointsController.class);
	@Resource(name = "purchasePointsServiceImpl")
	private IPurchasePointsService purchasePointsService;
	@Autowired
	private IFlightOrderService flightOrderService;
	@Resource
	private PurchasePointsDubboService purchasePointsDubboService;
	@Resource
	private IUniConfigManagerWS uniConfigManagerWS;

	@RequestMapping(value = "/doInsertPurchasePoints", method = RequestMethod.POST)
	@ResponseBody
	public PurchasePointsRes doInsertPurchasePoints(HttpServletResponse response, HttpServletRequest request, @RequestBody PurchasePointsReq vo) throws ActionException {
		try {
			log.info("插入积分购买数据" + JSONObject.toJSONString(vo));
			Long channelCode = purchasePointsDubboService.getChannelCode(vo.getSite());
			String currencyCode = purchasePointsDubboService.getCurrencyCode(channelCode);
			vo.setChannelCode(channelCode.toString());
			vo.setCurrency(currencyCode);
			vo.setSourceIp(HttpUtils.getIpAddr(request));
			UniRateRQ rq = new UniRateRQ();
			rq.setConversion("CNY");
			BigDecimal rate = uniConfigManagerWS.getDefRateByConversion(rq).getCurrRate().get(currencyCode);
			vo.setRate(rate);
			PurchasePointsRes doInsertPurchasePoints = purchasePointsService.doInsertPurchasePoints(vo);
			log.info("插入数据成功" + JSONObject.toJSONString(vo));
			return doInsertPurchasePoints;
		}catch(Exception e) {
			log.error("插入积分购买数据" + JSONObject.toJSONString(vo),e);
			return null;
		}
	}

	@RequestMapping(value = "/getPurchasePointsVOByOrderNo", method = RequestMethod.GET)
	@ResponseBody
	public PurchasePointsDetailsResultVO getPurchasePointsVO(HttpServletResponse response, HttpServletRequest request, @RequestParam String orderNo, @CookieValue(value = "global_site_flag", defaultValue = "en_US") String site) throws ActionException {
		PurchasePointsDetailsResultVO result = new PurchasePointsDetailsResultVO();
		log.info("通过大订单获取积分购买数据开始");
		List<PurchasePointsVO> purchasePointsDetails = purchasePointsService.getPurchasePointsDetailsByOrderNo(orderNo);
		if (!CollectionUtils.isEmpty(purchasePointsDetails)) {
			PurchasePointsVO purchasePointsVO = purchasePointsDetails.get(0);
			Date date = new Date();
			Long time = (date.getTime() - purchasePointsVO.getCreateDt().getTime());
			// 获取支付倒计时
			UniConfigRS uniConfigRS = uniConfigManagerWS.findSiteInfo2ByChannel(purchasePointsDubboService.getChannelCode(site));
			Long comeLeaveTime = uniConfigRS.getUniconfigVO().getCtdTime();
			log.info("通过大订单获取积分购买数据成功");
			result.setLeftTime(comeLeaveTime - time);
			result.setVos(purchasePointsDetails);
			try {
				log.info("开始查询booking单号,对应积分购买"+purchasePointsVO.getPurchasePointsNo());
		        BookingOrderMoreParam bookingOrderMoreParam = new BookingOrderMoreParam();
		        bookingOrderMoreParam.setPurchasePointsOrderNo(purchasePointsVO.getPurchasePointsNo());
		        List<BookingOrderDto> bookingOrderDtoList = flightOrderService.getBookingOrderDtoListByMoreParam(bookingOrderMoreParam);
		        String bookingOrderNo = bookingOrderDtoList.get(0).getBookingOrderNo();  
		        Integer source = bookingOrderDtoList.get(0).getSource();
		        result.setBookingOrderNo(bookingOrderNo);
		        result.setSource(source);
			}catch(Exception e) {
				log.error(purchasePointsVO.getPurchasePointsNo(),e);
			}
		}
		return result;
	}

	@RequestMapping(value = "/getAllPurchasePointsVO", method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> getAllPurchasePointsVO(HttpServletResponse response, 
														 HttpServletRequest request, 
														 @RequestParam(required = false) String startDate,
														 @RequestParam(required = false) String endDate,
														 @RequestParam(required = false) int currPage,
														 @RequestParam(required = false) int pageSize,
														 @CookieValue(value = "global_site_flag",defaultValue = "") String site) throws ActionException {
		log.info("通过大订单获取积分购买数据开始");
		UserInfoBean userInfoBean = UserContext.getUser(request);
	    if(null == userInfoBean || null == userInfoBean.getCustomerid() || "".equals(userInfoBean.getCustomerid())) {
	    	throw new ActionException(GlobalExceptionConstants.MEMBER_000000);
	    }
	    Map<String,Object> purchasePointsList = purchasePointsService.getPurchasePointsList(userInfoBean.getCustomerid(),startDate,endDate,site,currPage,pageSize);
		log.info("通过大订单获取积分购买数据成功");
		return purchasePointsList;
	}

}
